package com.dnndo.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.dnndo.common.annotation.Log;
import com.dnndo.common.core.controller.BaseController;
import com.dnndo.common.core.domain.AjaxResult;
import com.dnndo.common.core.domain.PageResult;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.core.domain.entity.SysRole;
import com.dnndo.common.core.domain.model.LoginUser;
import com.dnndo.common.enums.BusinessType;
import com.dnndo.common.utils.StringUtils;
import com.dnndo.common.utils.bean.BeanDtoVoUtil;
import com.dnndo.framework.aspectj.DataScopeAspect;
import com.dnndo.framework.web.service.SysPermissionService;
import com.dnndo.framework.web.service.TokenService;
import com.dnndo.system.domain.dto.SysRoleDTO;
import com.dnndo.system.domain.dto.SysRoleInsertDTO;
import com.dnndo.system.domain.dto.SysRoleUpdStatusDTO;
import com.dnndo.system.domain.dto.SysRoleUpdateDTO;
import com.dnndo.system.domain.vo.SysRoleVO;
import com.dnndo.system.mapper.SysRoleMenuMapper;
import com.dnndo.system.service.ISysRoleService;
import com.dnndo.system.service.ISysUserService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
  @Autowired
  private ISysRoleService roleService;

  @Autowired
  private TokenService tokenService;

  @Autowired
  private SysPermissionService permissionService;

  @Autowired
  private ISysUserService userService;

  @Autowired
  private SysRoleMenuMapper roleMenuMapper;

  /**
   * 角色列表
   */
  @PreAuthorize("@ss.hasPermi('system:role:list')")
  @GetMapping("/list")
  public PageResult<SysRoleVO> list(SysRoleDTO dto) {
    startPage();
    List<SysRole> list = roleService.selectRoleList(BeanDtoVoUtil.convert(dto, SysRole.class));
    return PageResult.pageOk(BeanDtoVoUtil.listVo(list, SysRoleVO.class), new PageInfo<>(list).getTotal());
  }

  @GetMapping("/rolelists")
  public AjaxResult lists(SysRoleDTO dto) {
    List<SysRole> list = roleService.selectRoleLists(BeanDtoVoUtil.convert(dto, SysRole.class));
    return AjaxResult.success(BeanDtoVoUtil.listVo(list, SysRoleVO.class));
  }

  /**
   * 根据角色编号获取详细信息
   */
  @PreAuthorize("@ss.hasPermi('system:role:getInfo')")
  @GetMapping(value = "/getInfo")
  public R<SysRoleVO> getInfo(@ApiParam(value = "角色ID", required = true) Long roleId) {
    if (roleId == null || roleId <= 0) {
      return R.fail("角色ID不能为空");
    }

    //检查数据权限
    roleService.checkRoleDataScope(roleId);
    //获取角色信息并转换
    SysRoleVO roleVO = BeanDtoVoUtil.convert(roleService.selectRoleById(roleId), SysRoleVO.class);
    //获取菜单id
    List<Long> menuIds = roleMenuMapper.selectMenuIdsByRoleId(roleId);
    // 写入菜单id
    roleVO.setCheckedKeys(menuIds);
    return R.ok(roleVO);
  }

  /**
   * 新增角色
   */
  @PreAuthorize("@ss.hasPermi('system:role:add')")
  @Log(title = "角色管理", businessType = BusinessType.INSERT)
  @PostMapping("/add")
  public AjaxResult add(@Validated @RequestBody SysRoleInsertDTO dto) {
    SysRole role = BeanDtoVoUtil.convert(dto, SysRole.class);
    if (!roleService.checkRoleNameUnique(role)) {
      return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
    } else if (!roleService.checkRoleKeyUnique(role)) {
      return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
    }
    role.setCreateBy(getUserId().toString());
    role.setCreateTime(new Date());
    role.setDataScope(DataScopeAspect.DATA_SCOPE_SELF);
    role.setDelFlag("0");

    int rows = roleService.insertRole(role);
    return toAjax(rows);

  }

  /**
   * 修改保存角色
   */
  @PreAuthorize("@ss.hasPermi('system:role:edit')")
  @Log(title = "角色管理", businessType = BusinessType.UPDATE)
  @PostMapping("/edit")
  public AjaxResult edit(@Validated @RequestBody SysRoleUpdateDTO dto) {
    SysRole role = BeanDtoVoUtil.convert(dto, SysRole.class);
    roleService.checkRoleAllowed(role);
    roleService.checkRoleDataScope(role.getRoleId());
    if (!roleService.checkRoleNameUnique(role)) {
      return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
    } else if (!roleService.checkRoleKeyUnique(role)) {
      return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
    }
    role.setUpdateBy(getUserId().toString());
    role.setUpdateTime(new Date());
    if (roleService.updateRole(role) > 0) {
      // 更新缓存用户权限
      LoginUser loginUser = getLoginUser();
      if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
        loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
        loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
        tokenService.setLoginUser(loginUser);
      }
      return success();
    }
    return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
  }

  /**
   * 状态修改
   */
  @PreAuthorize("@ss.hasPermi('system:role:changeStatus')")
  @Log(title = "角色管理", businessType = BusinessType.UPDATE)
  @PostMapping("/changeStatus")
  public AjaxResult changeStatus(@RequestBody @Validated SysRoleUpdStatusDTO dto) {
    SysRole role = BeanDtoVoUtil.convert(dto, SysRole.class);
    roleService.checkRoleAllowed(role);
    roleService.checkRoleDataScope(role.getRoleId());
    role.setUpdateBy(getUserId().toString());
    role.setUpdateTime(new Date());
    int row = roleService.updateRoleStatus(role);
    return toAjax(row);
  }

  /**
   * 删除角色
   */
  @PreAuthorize("@ss.hasPermi('system:role:del')")
  @Log(title = "角色管理", businessType = BusinessType.DELETE)
  @GetMapping("/del")
  public AjaxResult del(@ApiParam(value = "角色ID", required = true) Long roleId) {
    if (roleId == null || roleId <= 0) {
      return error("角色ID不能为空");
    }
    int row = roleService.deleteRoleById(roleId);
    return toAjax(row);
  }
}
